import { animationPool } from "@/animationPool";
import { EGamePadAxes } from "@/enums/gamepad.enum";
import { qino } from "@/objects/meshs/qino.mesh";

class MyGamePad {
  name: string = "gamepad";
  constructor() {

  }
  init() {
    window.addEventListener("gamepadconnected", (evt: GamepadEvent) => {
      evt.preventDefault();
      console.log(
        `第${evt.gamepad.index}位： 
${evt.gamepad.id}
${evt.gamepad.buttons.length} 个按钮，
${evt.gamepad.axes.length} 个坐标方向。`
      );

      animationPool.set(this.name, () => {
        const gamepads = navigator.getGamepads();
        const gamepad0 = gamepads[0];
        // const gamepad1 = gamepads[1];
        // const gamepad2 = gamepads[2];
        // const gamepad3 = gamepads[3];
        if (gamepad0) {
          gamepad0.buttons.forEach((btn, idx) => {
            if (btn.pressed) {
              console.log(`第${idx}个按钮被按下`, btn.value);
            }
          });
          const axes = gamepad0.axes.map(v => -0.2 <= v && v <= 0.2 ? 0 : v);
          
          qino.gamepadUpdate(
            [
              axes[EGamePadAxes.lh],
              axes[EGamePadAxes.lv],
              axes[EGamePadAxes.rh],
              axes[EGamePadAxes.rv],
            ],
            gamepad0.buttons
          );
        }
      });
    });
    window.addEventListener("gamepaddisconnected", (evt: GamepadEvent) => {
      console.log("控制器已从 %d 位断开：%s", evt.gamepad.index, evt.gamepad.id);
      animationPool.delete(this.name);
    });
  }
}

export const gamepad = new MyGamePad();
